package com.example.votingsystem.controller;

import com.example.votingsystem.entity.VoteTopic;
import com.example.votingsystem.entity.VoteOption;
import com.example.votingsystem.entity.VoteRecord;
import com.example.votingsystem.security.UserPrincipal;
import com.example.votingsystem.service.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/vote")
@CrossOrigin(origins = "*")
public class VoteController {

    @Autowired
    private VoteService voteService;

    @GetMapping("/active")
    public ResponseEntity<List<VoteTopic>> getActiveVotes() {
        return ResponseEntity.ok(voteService.getActiveVoteTopics());
    }

    @GetMapping("/upcoming")
    public ResponseEntity<List<VoteTopic>> getUpcomingVotes() {
        return ResponseEntity.ok(voteService.getUpcomingVotes());
    }

    @GetMapping("/popular")
    public ResponseEntity<List<VoteTopic>> getPopularVotes() {
        return ResponseEntity.ok(voteService.getPopularVotes());
    }

    @PostMapping("/cast")
    public ResponseEntity<?> castVote(
            @AuthenticationPrincipal UserPrincipal currentUser,
            @RequestBody Map<String, Long> voteRequest) {
        VoteRecord record = voteService.castVote(
            currentUser.getId(),
            voteRequest.get("topicId"),
            voteRequest.get("optionId")
        );
        return ResponseEntity.ok(record);
    }

    @GetMapping("/history")
    public ResponseEntity<List<VoteRecord>> getVoteHistory(@AuthenticationPrincipal UserPrincipal currentUser) {
        return ResponseEntity.ok(voteService.getUserVoteHistory(currentUser.getId()));
    }

    @PostMapping("/topic")
    public ResponseEntity<VoteTopic> createVoteTopic(@RequestBody VoteTopic voteTopic) {
        return ResponseEntity.ok(voteService.createVoteTopic(voteTopic));
    }

    @PostMapping("/option")
    public ResponseEntity<VoteOption> addVoteOption(@RequestBody VoteOption voteOption) {
        return ResponseEntity.ok(voteService.addVoteOption(voteOption));
    }
}
